﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Xml.Linq;

namespace DailyRssDownload.Lib {
	public class Log {
		public static void LogError(Exception ex) {
			string strLogDirectory = GetLogDirectory();
			string strLogLocation = Path.Combine(strLogDirectory, "DailyRssDownloadErrors.xml");

			XElement elementError = CreateElementFromException(ex);

			AddInnerExceptions(ex, elementError);

			XDocument docXmlFile;
			XElement elementRoot;
			if (File.Exists(strLogLocation)) {
				docXmlFile = XDocument.Load(strLogLocation);
				elementRoot = docXmlFile.Element("exceptions");
			} else {
				docXmlFile = new XDocument();
				elementRoot = new XElement("exceptions");
				docXmlFile.Add(elementRoot);
				
			}
			elementRoot.Add(elementError);
			docXmlFile.Save(strLogLocation);
		}

		private static XElement CreateElementFromException(Exception ex) {
			XElement elementException = new XElement("exception");

			elementException.Add(new XAttribute("type", ex.GetType().ToString()));
			elementException.Add(new XAttribute("message", ex.Message));
			if (ex.StackTrace != null)
				elementException.Add(new XAttribute("stacktrace", ex.StackTrace));

			return elementException;
		}

		private static void AddInnerExceptions(Exception ex, XElement elementError) {
			if (ex.InnerException != null) {
				XElement elementInnerError = CreateElementFromException(ex.InnerException);
				elementError.Add(elementInnerError);
				AddInnerExceptions(ex.InnerException, elementInnerError);
			}
		}

		private static string GetLogDirectory() {
			try {
				Settings objSettings = new Settings();
				return objSettings.DownloadLocation;
			} catch {
				return Directory.GetCurrentDirectory();
			}
		}
	}
}
